<template>
  <div class="login-container">
    <van-nav-bar
      title="登录/注册"
      left-arrow
      class="app-nav-bar"
      @click-left='$router.back()'
    />

    <!-- 表单数据 -->
    <van-form
     @submit="handleOnLogin"
     @failed='handleFormFail'
     :show-error='false'
     :show-error-message='false'
     ref="login-form"
     >
      <van-field
        v-model="user.mobile"
        icon-prefix='icon'
        left-icon="shouji"
        placeholder="请输入手机号"
        name="mobile"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        clearable
        icon-prefix='icon'
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-button size="mini" round  class="send-btn" @click="handleSendCode" native-type="button" v-if="!isCountDownShow" :loading='isSendSmsLoading'>发送验证码</van-button>
          <van-count-down format="ss s" :time="1000*5" v-else @finish='isCountDownShow = false'></van-count-down>
        </template>
      </van-field>
       <!-- 登录按钮 -->
      <div class="login-btn-wrap">
        <van-button type="info" block class="login-btn" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
import { Toast } from 'vant'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        mobile: '17090086870',
        code: '246810'
      },
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机格式有误' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式有误' }
        ]
      },
      isCountDownShow: false,
      isSendSmsLoading: false // 发送验证码的loading状态, 防止网络慢多点
    }
  },
  computed: {},
  mounted () {},
  methods: {
    async handleOnLogin () {
      Toast.loading({
        message: '登录中....',
        forbidClick: true, // 禁止点击背景
        duration: 0 // 为0时不会自动隐藏
      })
      try {
        const { data } = await login(this.user)
        this.$store.commit('setUser', data.data)
        Toast.success('登录成功')
        // 清除layout的缓存, 让他重新渲染
        this.$store.commit('removeCachePage', 'LayoutIndex')

        // 登录成功, 调回原来的页面
        // this.$router.back() // 这种方式不太好
        this.$router.push(this.$route.query.redirect || '/')
      } catch (err) {
        console.log(err)
        console.log('登录失败', err)
        Toast.fail('登录失败, 手机号或者验证码错误')
      }
    },
    // 表单验证不通过时执行
    handleFormFail (error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: top
        })
      }
    },

    // 发送验证码
    async handleSendCode () {
      // 验证手机号码
      // 传入表单项的name单独触发验证
      try {
        await this.$refs['login-form'].validate('mobile')
        this.isSendSmsLoading = true
        await sendSms(this.user.mobile)
        // 发送成功, 倒计时
        this.isCountDownShow = true
      } catch (err) {
        //  try 里面任何代码的错误都会进入catch
        // 不同的错误需要不同的提示, 那就需要判断了
        let message = ''
        if (err.name === 'mobile') {
          message = err.message
        } else if (err && err.response && err.response.status === 429) {
          message = '发送太频繁了, 请稍后重试'
        } else {
          message = '发送失败, 请稍后重试'
        }
        this.$toast.fail({
          message: message,
          position: 'top'
        })
      }
      this.isSendSmsLoading = false // 无论发送成功还是失败都要关闭
      // 验证通过 -> 请求发送验证码 -> 用户接收短信 -> 输入验证码 -> 请求登录
      // 请求发送验证码 -> 显示倒计时
    }
  }
}
</script>
<style lang='less' scoped>
.login-container {
    .send-btn {
      width: 76px;
      height: 23px;
      background-color: #ededed;
      color: #666;
      font-size: 11px;
    }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: 0;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
